
/* 描绘更大分辨率像素图 */
export const generateRenderMap = function( w, h, ctx, resolution ) {
  var pixelMap = [];
  for( let y = 1; y < h; y += resolution ) {
    for( let x = 1; x < w; x += resolution ) {
      // 获取当前位置的像素群
      const pixel = ctx.getImageData( x, y, resolution, resolution );
      let len = pixel.data.length / 4;
      let r = pixel.data[0],
          g = pixel.data[1],
          b = pixel.data[2];
      if( r <= 136 && (g < 132 && g > 60) && b <= 36 ) {
        pixelMap.push( {x: x, y: y} );
      }
    }
  }
  return {
    data: pixelMap,
    resolution: resolution
  };
}


/* 盒模型测试， 碰撞返回 true */
export const hitBox = function( source, target ) {
  /* 源物体和目标物体都包含 x, y 以及 width, height */
  return !(
    ( ( source.y + source.height ) < ( target.y ) ) ||
    ( source.y > ( target.y + target.height ) ) ||
    ( ( source.x + source.width ) < target.x ) ||
    ( source.x > ( target.x + target.width ) )
  );
}


/* 像素碰撞测试 */
export const pixelHitTest = function( source, target ) {

  // 循环源对象的所有像素
  for( var s = 0; s < source.data.length; s++ ) {
    var sourcePixel = source.data[s];
    // 添加位置偏移
    var sourceArea = {
      x: sourcePixel.x ,
      y: sourcePixel.y ,
      width: source.resolution,
      height: source.resolution
    };

    var targetArea = {
      x: target.x ,
      y: target.y ,
      width: 1,
      height: 1
    };

    if( hitBox( sourceArea, targetArea ) ) {
      return true;
    }
  }
}
